<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/23
 * Time: 下午12:28
 */

namespace common\jobs;

use common\models\Coupon;
use common\models\CouponCategory;
use common\models\UserCoupon;
use yii\base\BaseObject;
use yii\queue\JobInterface;
use yii\queue\Queue;
use yii;

class UpdateCouponJob extends BaseObject implements JobInterface
{

    public $markId;
    public $couponOriginId;
    public $userId;
    public $couponType;
    public $catalog;
    public $couponId;

    /**
     * @param Queue $queue which pushed and is handling the job
     */
    public function execute($queue)
    {
        //CouponCategory::TYPE_NUM_MANY=2 一码多用
        //CouponCategory::TYPE_NUM_ONE=1  一码一用
        $model = UserCoupon::find()->where(['user_id' => $this->userId, 'coupon_id' => $this->couponId, 'mark_id' => $this->markId])->one();
        if ($model == null) {
            $model = new UserCoupon();
            $model->attempt = 1;
        } else {
            $model->attempt = $model->attempt + 1;
        }

        $model->user_id = $this->userId;
        $model->coupon_id = $this->couponId;
        $model->catalog = $this->catalog;
        $model->mark_id = $this->markId;
        $model->created_at = $model->updated_at = time();

        if ($this->couponType == CouponCategory::TYPE_NUM_MANY) {

            $sql = "UPDATE wmtg_coupon SET use_num = use_num + 1 WHERE origin_id =" . $this->couponOriginId;
        } else {
            $status = Coupon::STATUS_INVALID;
            $sql = "UPDATE wmtg_coupon SET status = $status WHERE origin_id =" . $this->couponOriginId;
        }

        try {
            Yii::$app->db->createCommand($sql)->execute();
            $model->status = UserCoupon::STATUS_OK;
            $model->save();
            return true;
        } catch (\Exception $e) {
            $model->status = UserCoupon::STATUS_ERROR;
            $model->error_msg = $e->getMessage();
            $model->save();
            throw $e;
        }
    }

    /**
     * @return int time to reserve in seconds
     */
    public function getTtr()
    {
        return 3;
    }

    /**
     * @param int $attempt number
     * @param \Exception $error from last execute of the job
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        return $attempt < 30;
    }
}
